import React, { Component } from 'react';
import { Input, Modal, Form, message } from 'antd';
import PropTypes from 'prop-types';
import _ from 'lodash';
import { addPort, modPort } from '@api/task';
import { PORT_RE, PORT_RANGE_RE, MAX_DETECTION_PORT, NAME_RE } from '@util/constants';
import validatorCreator from '@util/validator-creator';
import getPortsCount from '@util/get-ports-count';
import './index.less';

const FormItem = Form.Item;
const TextArea = Input.TextArea;
const prefixCls = 'port-manage-modal';

const formItemLayout = {
  labelCol: {
    span: 4
  },
  wrapperCol: {
    span: 20
  }
};

class PortManageModal extends Component {
  constructor(props) {
    super(props);
  }

  UNSAFE_componentWillReceiveProps(props) {
    const {
      detail = {},
      form: { setFieldsValue, getFieldsValue },
      isAddPort = false
    } = props;
    if (this.props.detail !== props.detail) {
      const port = _.get(detail, 'ports', []).join(',');
      const name = _.get(detail, 'name', '');
      const newValue = { port, name };
      setFieldsValue(newValue);
    }

    let { port, name } = getFieldsValue(['port', 'name']);
    if (!this.props.modalVisible && isAddPort && (port || name)) {
      const newValue = { port: '', name: '' };
      setFieldsValue(newValue);
    }
  }

  addPortSuccess = () => {
    this.props.changeModalVisible(false, {});
    this.props.getPortList();
  };

  portsValidate = (rule, value, callback) => {
    if (!value) {
      callback('端口不能为空');
    }
    let ports = value.split(',');
    ports.map(item => {
      if (!PORT_RE.test(item) && !PORT_RANGE_RE.test(item)) {
        callback('请输入正确格式的端口');
      }
    });
    if (getPortsCount(ports) > MAX_DETECTION_PORT) {
      callback(`端口数不能超过${MAX_DETECTION_PORT}`);
    }
    callback();
  };

  onClickSubmit = () => {
    const {
      form: { validateFieldsAndScroll }
    } = this.props;
    validateFieldsAndScroll((err, values) => {
      if (err) {
        return;
      }
      const formatedData = {
        name: values.name.replace(/\s/g, ''),
        ports: _.uniq(values.port.split(','))
      };

      // 20190626 添加失败却无报错bug
      // this.setState({ loading: true });

      let todo, successInfo, errorInfo, body;
      if (this.props.detail) {
        todo = modPort;
        successInfo = '修改成功';
        errorInfo = '修改失败';

        body = { port_id: _.get(this.props.detail, '_id', '') };
      } else {
        todo = addPort;
        successInfo = '添加成功';
        errorInfo = '添加失败';
        body = {};
      }

      // 20190626 修复添加失败却无报错bug，将57行代码移至下面。
      // 推测为react setState异步更新导致的bug，具体原因还未找出
      this.setState({ loading: true });

      todo({ ...body, ...formatedData })
        .then(() => {
          message.success(successInfo);
          this.setState({ loading: false }, this.addPortSuccess);
        })
        .catch(err => {
          message.error(err.message || errorInfo);
          this.setState({ loading: false });
        });
    });
  };

  render() {
    const { modalVisible = false, detail = {} } = this.props;
    const {
      form: { getFieldDecorator }
    } = this.props;
    const ports = _.get(detail, 'ports', []);
    const portName = _.get(detail, 'name', '');
    return (
      <div className="password-modal">
        <Modal
          maskClosable={false}
          title={
            <span style={{ fontWeight: 600 }}>{detail._id ? '修改' : '添加'}端口策略模版</span>
          }
          className={`${prefixCls}-modal`}
          visible={modalVisible}
          width={520}
          portManage
          onCancel={() => this.props.changeModalVisible(false)}
          onOk={this.onClickSubmit}
          okButtonProps={{ className: 'button-forwards' }}
        >
          <Form labelAlign="left">
            <FormItem {...formItemLayout} key="name" label="名称" colon={false}>
              {getFieldDecorator('name', {
                rules: [
                  {
                    validator: validatorCreator('名称', {
                      required: true
                    })
                  },
                  {
                    pattern: NAME_RE,
                    message: '您输入的格式有误，仅支持中文、英文、数字、特殊字符 - 、— \\ _ / ：~'
                  },
                  {
                    max: 32,
                    message: '您输入的内容超过32个字符限制'
                  }
                ],
                initialValue: detail && portName
              })(<Input placeholder="请输入中文、英文、特殊字符或数字，不超过32个字符" />)}
            </FormItem>
            <FormItem {...formItemLayout} key="port" label="端口" colon={false}>
              {getFieldDecorator('port', {
                rules: [{ validator: this.portsValidate }],
                initialValue: detail && ports
              })(
                <TextArea
                  rows={4}
                  placeholder="请使用“-”指定端口范围，使用“，”分割端口。&#10;例如：21，22，23，10-50"
                />
              )}
            </FormItem>
          </Form>
        </Modal>
      </div>
    );
  }
}

PortManageModal.propTypes = {
  form: PropTypes.object.isRequired,
  changeModalVisible: PropTypes.function,
  modalVisible: PropTypes.boolean,
  getPortList: PropTypes.function,
  detail: PropTypes.object,
  isAddPort: PropTypes.boolean
};

export default Form.create()(PortManageModal);
